package mylibrary.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {

	private static final int PORT = 19527;
	
	private ExecutorService pool = null;
	
	private ServerSocket serverListenSocket;
	
	private int times = 5;
	
	public void start() {
		
		pool = Executors.newFixedThreadPool(10);
		
		try {
			serverListenSocket = new ServerSocket(PORT);
			serverListenSocket.setReuseAddress(true);
			System.out.println("I'm listening");
			
			while(times-- > 0) {
				Socket socket = serverListenSocket.accept();
				String welcomeString = "Hello";
				pool.execute(new ServiceThread(socket));
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		cleanUp();
	}
	
	public void cleanUp() {
		if(serverListenSocket != null) {
			try {
				serverListenSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		pool.shutdown();
	}
	
	public static void main(String[] args) {
		Server server = new Server();
		server.start();
	}
}
